#include "CSpider.h"


CSpider::CSpider(IrrlichtDevice* device, vector3df& position)
{
	smgr = device->getSceneManager();
	driver = device->getVideoDriver();
	
	node = smgr->addMeshSceneNode(smgr->getMesh(L"data/spider/spider.b3d"));
	
	// Different textures for the spider model
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_001.tga"));
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_black_red.tga"));
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_blue_red.tga"));
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_green_purple.tga"));
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_turquoise_purple.tga"));
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_yellow_brown.tga"));
	texture.push_back(driver->getTexture(L"data/spider/tex_spider_yellow_red.tga"));

	if (node)
	{
		// Generate texture number and set material texture
		node->setMaterialTexture(0, texture[genRandomInt(0, texture.size()-1)]);
		
		node->setMaterialFlag(EMF_LIGHTING, false);
		node->setPosition(position);
	}

	// Spider movement speed
	speed = 4.f;
}


CSpider::~CSpider(void)
{
	kill();
}


void CSpider::update(vector3df& target)
{
	// Rotate to target
	vector3df difference = vector3df(node->getPosition() - target);
	node->setRotation(difference.getHorizontalAngle());
	
	// Update position
	node->setPosition(node->getPosition() - speed * vector3df(
		sin(node->getRotation().Y * DEGTORAD), 0, cos(node->getRotation().Y * DEGTORAD)));
}


void CSpider::kill(void)
{
	texture.clear();
	node->remove();
}


bool CSpider::checkCollision(IAnimatedMeshSceneNode* nodeToCheck)
{
	if (node->getTransformedBoundingBox().intersectsWithBox(nodeToCheck->getTransformedBoundingBox()))
	{
		return true;
	}
	// No collision
	return false;
}


IMeshSceneNode* CSpider::getNode()
{
	return node;
}